package cn.kgc.springbootdemo.config.web;

import cn.hutool.core.lang.Validator;
import cn.hutool.core.util.ObjectUtil;
import cn.kgc.springbootdemo.annotation.PassToken;
import cn.kgc.springbootdemo.annotation.UserLoginToken;
import cn.kgc.springbootdemo.entity.User;
import cn.kgc.springbootdemo.enums.ResultEnum;
import cn.kgc.springbootdemo.exception.HandleException;
import cn.kgc.springbootdemo.service.UserService;
import cn.kgc.springbootdemo.util.TokenUtil;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.exceptions.JWTVerificationException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

/**
 * <h3>springbootdemo</h3>
 * <p></p>
 *
 * @author : DongZeJian
 * @date : 2020-07-17 16:19
 **/
public class AuthenticationInterceptor implements HandlerInterceptor {

    @Autowired
    UserService userService;

    @Autowired
    private TokenUtil tokenUtil;

    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object object) throws Exception {

        String token =httpServletRequest.getHeader("Authorization");// 从 http 请求头中取出 token

        HandlerMethod handlerMethod=(HandlerMethod)object;
        Method method=handlerMethod.getMethod();

        //检查是否有passtoken注释，有则跳过认证
        if (method.isAnnotationPresent(PassToken.class)) {
            PassToken passToken = method.getAnnotation(PassToken.class);
            if (passToken.required()) {
                return true;
            }
        }

        // 拦截的接口验证
        if(object instanceof HandlerMethod){

            Validator.validateNotEmpty(token, "token不能为空");

            // 获取 token 中的 user id
            String userID;
            try {
                userID = JWT.decode(token).getAudience().get(0);
            } catch (JWTDecodeException j) {
                throw new HandleException(ResultEnum.ACCESS_DENIED_ERROR);
            }

            User user = userService.findByUserID(userID);
            if (user == null) {
                throw new HandleException(ResultEnum.ERROR_CODE.getCode(),"用户不存在");
            }
            // 验证 token

            try {
                JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(user.getPasswrod())).build();
                jwtVerifier.verify(token);
            } catch (Exception e) {
                throw new HandleException(ResultEnum.ACCESS_DENIED_ERROR);
            }
            //判断是否已注销
            if (ObjectUtil.isNull(tokenUtil.getUser())){
                throw new HandleException(ResultEnum.ACCESS_DENIED_ERROR);
            }
            //放行后给redis重新续命10时间 来表示用户活跃访问
            tokenUtil.lives();
            return true;
        }

        //检查有没有需要用户权限的注解
        if (method.isAnnotationPresent(UserLoginToken.class)) {
            UserLoginToken userLoginToken = method.getAnnotation(UserLoginToken.class);
            if (userLoginToken.required()) {
                Validator.validateNotEmpty(token, "token不能为空");

                // 获取 token 中的 user id
                String userID;
                try {
                    userID = JWT.decode(token).getAudience().get(0);
                } catch (JWTDecodeException j) {
                    throw new HandleException(ResultEnum.ACCESS_DENIED_ERROR);
                }
                User user = userService.findByUserID(userID);
                if (user == null) {
                    throw new HandleException(ResultEnum.ERROR_CODE.getCode(),"用户不存在");
                }
                // 验证 token
                JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(user.getUserCode())).build();
                try {
                    jwtVerifier.verify(token);
                } catch (JWTVerificationException e) {
                    throw new HandleException(ResultEnum.ACCESS_DENIED_ERROR);
                }
                //判断是否已注销
                if (ObjectUtil.isNull(tokenUtil.getUser())){
                    throw new HandleException(ResultEnum.ACCESS_DENIED_ERROR);
                }
                return true;
            }
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }
    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }
}
